package com.im.service.investPlan.smo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.util.StringUtil;
import com.im.MDA;
import com.im.service.common.smo.ICommonSMO;
import com.im.service.dto.BaseException;
import com.im.service.dto.FileUpload;
import com.im.service.dto.FundSource;
import com.im.service.dto.InvestPlan;
import com.im.service.dto.PlanDeclareSet;
import com.im.service.dto.Staff;
import com.im.service.folderManage.dao.IFolderManageOperDAO;
import com.im.service.investPlan.dao.IInvestPlanOperDAO;
import com.im.service.investPlan.dao.IInvestPlanQueryDAO;
import com.im.service.model.PlanGreenReqVo;
import com.im.service.planDeclareSet.dao.IPlanDeclareSetQueryDAO;
import com.im.service.projectInfo.dao.IFundSourceOperDAO;
import com.im.service.projectInfo.dao.IFundSourceQueryDAO;
import com.im.util.DateUtil;
import com.im.util.JsonUtil;
import com.im.util.ListUtil;
import com.im.util.ReturnsUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class InvestPlanOperSMOImpl implements IInvestPlanOperSMO {

	private static final Logger logger = LogManager.getLogger(InvestPlanOperSMOImpl.class);
	@Autowired
	private IInvestPlanOperDAO investPlanOperDAO;
	@Autowired
	private IInvestPlanQueryDAO investPlanQueryDAO;
	@Autowired
	private IFundSourceQueryDAO fundSourceQueryDAO;
	@Autowired
	private IFundSourceOperDAO fundSourceOperDAO;
	@Autowired
	private IFolderManageOperDAO folderManageOperDAO;
    @Autowired
    private IPlanDeclareSetQueryDAO planDeclareSetQueryDAO;
    @Autowired
    ICommonSMO commonSMO;

	@Override
	public String addInvestPlanSet(String jsonStr, Staff staff) throws Exception {
		try {
			// 1.json格式校验
			if (!JsonUtil.jsonValidate(jsonStr)) {
				throw new BaseException(
						new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
			}
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取新增投资计划申报设置入参时：";
			// 2.获取入参 投资计划申报信息
			// String investPlanId = JsonUtil.getNotNullStringFromJSON(jsonObj,
			// "investPlanId", errorMsg);
			String investPlanName = JsonUtil.getNotNullStringFromJSON(jsonObj, "investPlanName", errorMsg);
			String investPlanCode = JsonUtil.getNotNullStringFromJSON(jsonObj, "investPlanCode", errorMsg);
			String enterRequest = JsonUtil.getNotNullStringFromJSON(jsonObj, "enterRequest", errorMsg);
			String statusCd = JsonUtil.getNotNullStringFromJSON(jsonObj, "statusCd", errorMsg);
			String yearDt = JsonUtil.getNotNullStringFromJSON(jsonObj, "yearDt", errorMsg);
			String endDt = JsonUtil.getNotNullStringFromJSON(jsonObj, "endDt", errorMsg);
			String description = JsonUtil.getStringFromJSON(jsonObj, "description", errorMsg);
			String declareType = JsonUtil.getStringFromJSON(jsonObj, "declareType", errorMsg);
			String docCode = JsonUtil.getNotNullStringFromJSON(jsonObj, "docCode", errorMsg);

			PlanDeclareSet investPlanSet = new PlanDeclareSet();
			// TODO 暂用UUID生成
			String declareSetId = UUID.randomUUID().toString();
			String investPlanId = UUID.randomUUID().toString();
			investPlanSet.setDeclareSetId(declareSetId);
			investPlanSet.setDeclareSetName(investPlanName);
			investPlanSet.setDeclareRelaObj(investPlanId);
			investPlanSet.setDescription(description);
			investPlanSet.setEnterRequest(enterRequest);
			investPlanSet.setDocCode(docCode);
			investPlanSet.setYearDt(yearDt);
			investPlanSet.setEndDt(endDt);
			investPlanSet.setStatusCd(statusCd);
			investPlanSet.setDeclareCode(investPlanCode);
			investPlanSet.setDeclareRelaType(MDA.DECLARE_RELA_TYPE_INVEST_PLAN);
			investPlanSet.setDeclareType(declareType);
			investPlanOperDAO.addInvestPlanSet(investPlanSet);
			
		/*	InvestPlan investPlan = new InvestPlan();
			investPlan.setInvestPlanId(investPlanId);
			investPlan.setInvestPlanName(investPlanName);
			investPlan.setImpleProjId(impleProjId);
			investPlan.setDeclareSetId(declareSetId);
			investPlan.setInvestPlanCode(investPlanCode);
			investPlan.setApplicant(staff.getStaffId());
			if(MDA.FUND_PLAN_STATUS_CD_WRITE.equals(Integer.valueOf(statusCd))){
				investPlan.setStatusCd(MDA.FUND_PLAN_STATUS_CD_WRITE.toString());
			}else{
				investPlan.setStatusCd(MDA.FUND_PLAN_STATUS_CD_APPLY.toString());
			}
			investPlanOperDAO.addInvestPlan(investPlan);
			
			// 5.新增资金信息
			FundSource fundSource = new FundSource();
			fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST);// 投资计划
			fundSource.setFundSourceObj(investPlanId);
			fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
			fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO
																					// 年度如何定
			Double fundSourceBu = 0D;
			Double fundSourceSheng = 0D;
			Double fundSourceGao = 0D;
			Double fundSourceQi = 0D;
			Double fundSourceShi = 0D;
			// 部补助
			if (fundSourceBu != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
				fundSource.setFundVal(fundSourceBu * 1000000 + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 省财政
			if (fundSourceSheng != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
				fundSource.setFundVal(fundSourceSheng * 1000000 + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 高速水运融资
			if (fundSourceGao != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
				fundSource.setFundVal(fundSourceGao * 1000000 + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 市州配套
			if (fundSourceShi != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
				fundSource.setFundVal(fundSourceShi * 1000000 + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 企业自筹
			if (fundSourceQi != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
				fundSource.setFundVal(fundSourceQi * 1000000 + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}*/
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
//			return ReturnsUtil.getStackTrackMessage(e);
//			throw new BaseException(ReturnsUtil.getStackTrackMessage(e));
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
//			return ReturnsUtil.getStackTrackMessage(e);
//			throw new Exception(ReturnsUtil.getStackTrackMessage(e));
		}
	}

	@Override
	public String updateInvestPlanSet(String jsonStr) throws Exception {
		try {
			// 1.json格式校验
			if (!JsonUtil.jsonValidate(jsonStr)) {
				throw new BaseException(
						new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
			}
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取修改投资计划申报设置入参时：";

			// 2.获取入参 投资计划申报信息
			String declareSetId = JsonUtil.getStringFromJSON(jsonObj, "declareSetId", errorMsg);
			String investPlanId = JsonUtil.getStringFromJSON(jsonObj, "investPlanId", errorMsg);
			String investPlanName = JsonUtil.getStringFromJSON(jsonObj, "investPlanName", errorMsg);
			String impleProjId = JsonUtil.getStringFromJSON(jsonObj, "impleProjId", errorMsg);
			String statusCd = JsonUtil.getStringFromJSON(jsonObj, "statusCd", errorMsg);
			String yearDt = JsonUtil.getNotNullStringFromJSON(jsonObj, "yearDt", errorMsg);
			String endDt = JsonUtil.getNotNullStringFromJSON(jsonObj, "endDt", errorMsg);
			String description = JsonUtil.getStringFromJSON(jsonObj, "description", errorMsg);
			String docCode = JsonUtil.getStringFromJSON(jsonObj, "docCode", errorMsg);
			String enterRequest = JsonUtil.getStringFromJSON(jsonObj, "enterRequest", errorMsg);

			PlanDeclareSet investPlanSet = new PlanDeclareSet();
			investPlanSet.setDeclareSetId(declareSetId);
			investPlanSet.setDeclareSetName(investPlanName);
			investPlanSet.setEnterRequest(enterRequest);
			investPlanSet.setDocCode(docCode);
			investPlanSet.setStatusCd(statusCd);
			investPlanSet.setYearDt(yearDt);
			investPlanSet.setEndDt(endDt);
			investPlanSet.setDescription(description);
			
			investPlanOperDAO.updateInvestPlanSet(investPlanSet);
			
			if (!MDA.DECLAE_SET_DOC_CANCEL.equals(statusCd)) {
			InvestPlan inPlan = new InvestPlan();
				inPlan.setInvestPlanId(investPlanId);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("investPlan", inPlan);
			InvestPlan investPlan = investPlanQueryDAO.queryInvestPlanDetail(paramMap);
			if(investPlan != null){
				String investPlanStatusCd = investPlan.getStatusCd();
					if (MDA.FUND_PLAN_STATUS_CD_APPLY.toString().equals(investPlanStatusCd)
						|| MDA.FUND_PLAN_STATUS_CD_WRITE.toString().equals(investPlanStatusCd)){
					InvestPlan iPlan = new InvestPlan();
						iPlan.setInvestPlanId(investPlanId);
					iPlan.setInvestPlanName(investPlanName);
					iPlan.setDeclareSetId(declareSetId);
						iPlan.setStatusCd(statusCd);
					iPlan.setImpleProjId(impleProjId);
					investPlanOperDAO.updateInvestPlan(iPlan);
				}else{
					return ReturnsUtil.returnFailure("当前投资计划状态不允许修改投资计划设置！");
				}
			}else{
				return ReturnsUtil.returnFailure("没有找到对应的投资计划！");
			}
			} else {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("declareSetId", declareSetId);
				investPlanOperDAO.deleteInvestPlan(paramMap);
			}
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
//			throw new BaseException(ReturnsUtil.getStackTrackMessage(e));
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
//			throw new Exception(ReturnsUtil.getStackTrackMessage(e));
		}
	}

	@Override
	public String updateInvestPlanSetByCondition(String jsonStr) throws Exception {
		try {
			// 1.json格式校验
			if (!JsonUtil.jsonValidate(jsonStr)) {
				throw new BaseException(
						new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
			}
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取修改投资计划申报设置入参时：";

			// 2.获取入参 投资计划申报信息
			//String declareSetIdStr = JsonUtil.getStringFromJSON(jsonObj, "declareSetIds", errorMsg);
			//List<String> declareSetIds = Arrays.asList(declareSetIdStr);
			List<String> declareSetIds = jsonObj.getJSONArray("declareSetIds");
			String statusCd = JsonUtil.getStringFromJSON(jsonObj, "statusCd", errorMsg);
			if(!ListUtil.isListEmpty(declareSetIds)){
				for(String declareSetId:declareSetIds){
					PlanDeclareSet investPlanSet = new PlanDeclareSet();
					investPlanSet.setDeclareSetId(declareSetId);
					investPlanSet.setStatusCd(statusCd);
					investPlanOperDAO.updateInvestPlanSet(investPlanSet);
				}
			}
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
		}
	}

	public void uploadFileDeal(String inJson, String uploadObjType, String uploadObjId) {
		JSONObject jsonObject = JSONObject.fromObject(inJson);
		JSONArray jsonArray = new JSONArray();
		if (jsonObject.containsKey("addFiles"))
			jsonArray = jsonObject.getJSONArray("addFiles");
		for (int i = 0; i < jsonArray.size(); i++) {
			String fileJson = jsonArray.getString(i).toString();
			String uploadName = JsonUtil.obtainValueFromJsonObject(fileJson, "attachFullName");// attachFullName
			String fileSuffix = JsonUtil.obtainValueFromJsonObject(fileJson, "attachSuffix");// attachSuffix
			String fileAttr = "10";
			String fileType = "10";
			String uploadSize = JsonUtil.obtainValueFromJsonObject(fileJson, "attachSize");// attachSize
			String filePath = JsonUtil.obtainValueFromJsonObject(fileJson, "attachPath");// attachPath
			String uploadDate = JsonUtil.obtainValueFromJsonObject(fileJson, "uploadDt");// uploadDt
			String uploadType = "";
			FileUpload fileUploadInfo = new FileUpload();
			if (!"".equals(fileSuffix)) {
				uploadType = (String) MDA.FILE_UPLOAD_TYPE.get(fileSuffix.toLowerCase());
			}
			String uploadId = UUID.randomUUID().toString();
			fileUploadInfo.setUploadId(uploadId);
			fileUploadInfo.setUploadName(uploadName);
			fileUploadInfo.setUploadObjType(uploadObjType);
			fileUploadInfo.setUploadObjId(uploadObjId);
			fileUploadInfo.setUploadType(uploadType);
			fileUploadInfo.setFileSuffix(fileSuffix);
			fileUploadInfo.setFileAttr(fileAttr);
			fileUploadInfo.setFileType(fileType);
			fileUploadInfo.setUploadSize(Long.valueOf(uploadSize));
			fileUploadInfo.setFilePath(filePath);
			fileUploadInfo.setUploadDate(uploadDate);
			folderManageOperDAO.insertFileUploadInfo(fileUploadInfo);
		}
		if (jsonObject.containsKey("delFiles")) {
			JSONArray deljsonArray = jsonObject.getJSONArray("delFiles");
			if (deljsonArray.size() > 0) {
				for (int i = 0; i < deljsonArray.size(); i++) {
					JSONObject item = deljsonArray.getJSONObject(i);
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("uploadId", item.getString("uploadId"));
					folderManageOperDAO.delFileUpload(param);
				}
			}
		}

	}

	@Override
	public String addInvestPlan(String jsonStr, Staff staff) throws Exception {
		try {
			// 1.json格式校验
			if (!JsonUtil.jsonValidate(jsonStr)) {
				throw new BaseException(
						new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
			}
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取新增投资计划入参时：";

			// 2.获取入参 投资计划信息
			String investPlanId = UUID.randomUUID().toString();
			String investPlanName = "默认";//JsonUtil.getStringFromJSON(jsonObj, "investPlanName", errorMsg);
			//String investPlanCode = JsonUtil.getNotNullStringFromJSON(jsonObj, "investPlanCode", errorMsg);
			String declareSetId = JsonUtil.getStringFromJSON(jsonObj, "declareSetId", errorMsg);
			String impleProjId = JsonUtil.getStringFromJSON(jsonObj, "impleProjId", errorMsg);
			String yearDt = JsonUtil.getStringFromJSON(jsonObj, "yearDt", errorMsg);
			String investPlanStartDt = JsonUtil.getStringFromJSON(jsonObj, "investPlanStartDt", errorMsg);
			String investPlanEndDt = JsonUtil.getStringFromJSON(jsonObj, "investPlanEndDt", errorMsg);
			String description = JsonUtil.getStringFromJSON(jsonObj, "description", errorMsg);
			String applicant = staff.getStaffId();
			// 3.获取入参 资金构成
			Double fundSourceBu = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceBu", errorMsg);
			Double fundSourceSheng = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceSheng", errorMsg);
			Double fundSourceGao = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceGao", errorMsg);
			Double fundSourceQi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceQi", errorMsg);
			Double fundSourceShi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceShi", errorMsg);
			Double fundSourceOther = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceOther", errorMsg);
			// 4.新增投资计划
			InvestPlan investPlan = new InvestPlan();
			investPlan.setDeclareSetId(declareSetId);
			investPlan.setInvestPlanId(investPlanId);
			//investPlan.setInvestPlanName(investPlanName);
			investPlan.setImpleProjId(impleProjId);
			if(investPlanStartDt != null){
				investPlan.setInvestPlanStartDt(investPlanStartDt);
			}
			if(investPlanEndDt != null){
				investPlan.setInvestPlanEndDt(investPlanEndDt);
			}

			// String statusCd = JsonUtil.obtainValueFromJsonObject(jsonStr,
			// "attachFullName");
			// if(statusCd != "") {
			// investPlan.setStatusCd(statusCd);
			// } else {
				investPlan.setStatusCd(MDA.FUND_PLAN_STATUS_CD_WAIT.toString());
			// }
			investPlan.setApplicant(applicant);
			//investPlan.setInvestPlanCode(investPlanCode);
			investPlan.setDescription(description);
			investPlan.setYearDt(yearDt);
			investPlan.setCreateDt(DateUtil.getNowDefault());
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("impleProjId", investPlan.getImpleProjId());
			paramMap.put("declareSetId", investPlan.getDeclareSetId());
			List<InvestPlan> list  = investPlanQueryDAO.queryInvestPlanListNew(paramMap);
			if(list != null && list.size() > 0){
				return "该申报批次与项目已存在!";
			}
			investPlanOperDAO.addInvestPlan(investPlan);

			// 5.新增资金信息
			FundSource fundSource = new FundSource();
			fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_ADD);// 投资计划
																					// 填报为301
			fundSource.setFundSourceObj(investPlanId);
			fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
			fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO
																					// 年度如何定
			// 部补助
			if (fundSourceBu != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
				fundSource.setFundVal(fundSourceBu + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 省财政
			if (fundSourceSheng != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
				fundSource.setFundVal(fundSourceSheng + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 高速水运融资
			if (fundSourceGao != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
				fundSource.setFundVal(fundSourceGao + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 市州配套
			if (fundSourceShi != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
				fundSource.setFundVal(fundSourceShi + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 企业自筹
			if (fundSourceQi != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
				fundSource.setFundVal(fundSourceQi + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 其他
			if (fundSourceOther != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_OTHER);
				fundSource.setFundVal(fundSourceOther + "");
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 下达文件入表
			uploadFileDeal(jsonStr, "150", investPlanId);
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
//			throw new BaseException(ReturnsUtil.getStackTrackMessage(e));
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
//			throw new Exception(ReturnsUtil.getStackTrackMessage(e));
		}
	}

	@Override
	public String updateInvestPlan(String jsonStr) throws Exception {
		try {
			// 1.json格式校验
			if (!JsonUtil.jsonValidate(jsonStr)) {
				throw new BaseException(
						new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
			}
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取修改投资计划填报入参时：";

			// 2.获取入参 投资计划信息
			String statusCd = JsonUtil.getStringFromJSON(jsonObj, "statusCd", errorMsg);
			String investPlanId = JsonUtil.getStringFromJSON(jsonObj, "investPlanId", errorMsg);
			if (MDA.FUND_PLAN_STATUS_CD_CANCEL.toString().equals(statusCd)) {
				
				// 1.更新投资计划
				InvestPlan delinvestPlan = new InvestPlan();
				delinvestPlan.setStatusCd(statusCd);
				delinvestPlan.setInvestPlanId(investPlanId);
				investPlanOperDAO.updateInvestPlanForDel(delinvestPlan);
				
				// 2.更新资金信息
				FundSource fundSource = new FundSource();
				fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_ADD);// 投资计划
				fundSource.setFundSourceObj(investPlanId);
				fundSource.setStatusCd(Integer.parseInt(MDA.INVALID_STATUS_CD));//失效
				fundSourceOperDAO.updateFundSource(fundSource);
				
//				InvestPlan delinvestPlan = new InvestPlan();
//				delinvestPlan.setStatusCd(statusCd);
//				delinvestPlan.setInvestPlanId(investPlanId);
//				investPlanOperDAO.updateInvestPlan(delinvestPlan);
				return ReturnsUtil.returnSuccess(new JSONObject()).toString();
			}

			String investPlanName = JsonUtil.getStringFromJSON(jsonObj, "investPlanName", errorMsg);
			String impleProjId = JsonUtil.getStringFromJSON(jsonObj, "impleProjId", errorMsg);
			String investPlanStartDt = JsonUtil.getStringFromJSON(jsonObj, "investPlanStartDt", errorMsg);
			String investPlanEndDt = JsonUtil.getStringFromJSON(jsonObj, "investPlanEndDt", errorMsg);

			String description = JsonUtil.getStringFromJSON(jsonObj, "description", errorMsg);
			// 3.获取入参 资金构成
			Double fundSourceBu = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceBu", errorMsg);
			Double fundSourceSheng = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceSheng", errorMsg);
			Double fundSourceGao = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceGao", errorMsg);
			Double fundSourceQi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceQi", errorMsg);
			Double fundSourceShi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceShi", errorMsg);
			Double fundSourceOther = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceOther", errorMsg);
			// 4.修改投资计划
			InvestPlan investPlan = new InvestPlan();
			investPlan.setInvestPlanId(investPlanId);
			investPlan.setInvestPlanName(investPlanName);
			investPlan.setImpleProjId(impleProjId);
			if(investPlanStartDt != null){
				investPlan.setInvestPlanStartDt(investPlanStartDt.substring(0, 4));
			}
			if(investPlanEndDt != null){
				investPlan.setInvestPlanEndDt(investPlanEndDt.substring(0, 4));
			}
			investPlan.setStatusCd(MDA.FUND_PLAN_STATUS_CD_WAIT.toString());
			investPlan.setDescription(description);

			investPlanOperDAO.updateInvestPlan(investPlan);

			// 5.更新资金信息
			FundSource fundSource = new FundSource();
			fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_ADD);// 301
			fundSource.setFundSourceObj(investPlanId);
			fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
			fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
			
			int num = 0;
			// 部补助
			if (fundSourceBu != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
				fundSource.setFundVal(fundSourceBu+"");
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			
			// 省财政
			if (fundSourceSheng != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
				fundSource.setFundVal(fundSourceSheng+"");
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 高速水运融资
			if (fundSourceGao != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
				fundSource.setFundVal(fundSourceGao+"");
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 市州配套
			if (fundSourceShi != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
				fundSource.setFundVal(fundSourceShi+"");
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 企业自筹
			if (fundSourceQi != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
				fundSource.setFundVal(fundSourceQi+"");
				fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 其他
			if (fundSourceOther != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_OTHER);
				fundSource.setFundVal(fundSourceOther + "");
				fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if (num == 0) {
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 下达文件入表
			uploadFileDeal(jsonStr, "150", investPlanId);
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
//			throw new BaseException(ReturnsUtil.getStackTrackMessage(e));
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
//			throw new Exception(ReturnsUtil.getStackTrackMessage(e));
		}
	}

	@Override
	public String batchTrialInvestPlan(String jsonStr) throws Exception {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		JSONArray planIds = jsonObj.getJSONArray("investPlanId");
		//String operType = JsonUtil.obtainValueFromJsonObject(jsonStr, "operType");
		String operType = JsonUtil.getStringFromJSON(jsonObj, "operType","获取操作类型时异常");
		String statusCd = JsonUtil.obtainValueFromJsonObject(jsonStr, "statusCd");
		String description = JsonUtil.obtainValueFromJsonObject(jsonStr, "examineDescription");
		for (int i = 0; i < planIds.size(); i++) {
			String investPlanId = planIds.getString(i);
			InvestPlan investPlan = new InvestPlan();
			investPlan.setInvestPlanId(investPlanId);
			investPlan.setStatusCd(statusCd);
			investPlan.setExamineDescription(description);
			investPlanOperDAO.updateInvestPlan(investPlan);
			// 查询已填报或已初审资金
			FundSource fundSource = new FundSource();
			if (StringUtil.isNotEmpty(operType) && "1".equalsIgnoreCase(operType)) {// 初审去查301的数据
				fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_ADD);
			} else {// 批复去查302的数据
				fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_TRIAL);
			}
			fundSource.setFundSourceObj(investPlanId);
			List<FundSource> fundSourceList = fundSourceQueryDAO.queryFoundSource(fundSource);
			for (FundSource fundSource2 : fundSourceList) {
				if (StringUtil.isNotEmpty(operType) && "1".equalsIgnoreCase(operType)) {
					fundSource2.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_TRIAL);
				} else {
					fundSource2.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_ALIGN);
				}
				fundSource2.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
				fundSource2.setFundSourceId(UUID.randomUUID().toString());
				fundSourceOperDAO.addFundSource(fundSource2);
			}
		}
		return ReturnsUtil.returnSuccess(new JSONObject()).toString();
	}

	/**
	 * 批复 ，绿色通道
	 * @param jsonStr
	 * @return
	 * @throws Exception 
	 */
	@Override
	public String addInvestPlanGreen(String jsonStr) throws Exception {

	    // 获取参数 各项金额，实施项目，建设单位，申报计划
        PlanGreenReqVo reqVo = JsonUtil.jsonToBean(jsonStr, PlanGreenReqVo.class);

        // 取 申报计划id
        String declareSetId = reqVo.getDeclareSetId();
        PlanDeclareSet planDeclareSet = planDeclareSetQueryDAO.queryPlanDeclareSet(declareSetId);
        // 回填 T_INVEST_PLAN 表，改状态
        String investPlanId = planDeclareSet.getDeclareRelaObj();
        // 查询 T_INVEST_PLAN 是否存在，存在则改状态，不存在，则增加
        InvestPlan investPlan = investPlanQueryDAO.queryInvestPlanById(investPlanId);
        if(investPlan!=null){
            investPlan.setStatusCd(reqVo.getStatusCd());
            investPlan.setVersion(DateUtil.getNowDefault());
            investPlanOperDAO.updateInvestPlan(investPlan);

            // 保存数据至 T_Fund_Source 表  FUND_SOURCE_OBJ_TYPE = 303
            addFundSourceForPlan(reqVo,investPlanId,MDA.FUND_SOURCE_OBJ_TYPE_INVEST_303);
        } else {

            // 4.新增投资计划
            investPlan = new InvestPlan();
            investPlan.setDeclareSetId(declareSetId);
            investPlan.setInvestPlanId(investPlanId);
            investPlan.setInvestPlanName(planDeclareSet.getDeclareSetName()+"-绿色审批");
            investPlan.setImpleProjId(reqVo.getImpleProjId());

            //MDA.FUND_PLAN_STATUS_CD_PASS.toString()
            investPlan.setStatusCd(reqVo.getStatusCd());
            investPlan.setApplicant(reqVo.getStaffId());

            String investPlanCode = commonSMO.querySeq("T_INVEST_PLAN");
            investPlan.setInvestPlanCode(investPlanCode);
            investPlan.setDescription(reqVo.getRemark()+"-绿色审批");
			// investPlan.setYearDt(DateUtil.getNowDefault().substring(0,4));
            investPlan.setCreateDt(DateUtil.getNowDefault());
            investPlanOperDAO.addInvestPlan(investPlan);

            // 保存数据至 T_Fund_Source 表  FUND_SOURCE_OBJ_TYPE = 303
            addFundSourceForPlan(reqVo,investPlanId,MDA.FUND_SOURCE_OBJ_TYPE_INVEST_301);
            addFundSourceForPlan(reqVo,investPlanId,MDA.FUND_SOURCE_OBJ_TYPE_INVEST_302);
            addFundSourceForPlan(reqVo,investPlanId,MDA.FUND_SOURCE_OBJ_TYPE_INVEST_303);
        }
        // 下达文件入表
        uploadFileDeal(jsonStr, "150", investPlanId);
        return ReturnsUtil.returnSuccess(new JSONObject()).toString();
	}

	public void addFundSourceForPlan(PlanGreenReqVo reqVo,String objId,String objType){

        FundSource fundSource = new FundSource();
        fundSource.setFundSourceObjType(objType);
        fundSource.setFundSourceObj(objId);
        fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
        fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO
        // 部补助
        if (StringUtil.isNotEmpty(reqVo.getBuFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
            fundSource.setFundVal(reqVo.getBuFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 省财政
        if (StringUtil.isNotEmpty(reqVo.getShengFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
            fundSource.setFundVal(reqVo.getShengFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 高速水运融资
        if (StringUtil.isNotEmpty(reqVo.getGaoFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
            fundSource.setFundVal(reqVo.getGaoFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 市州配套
        if (StringUtil.isNotEmpty(reqVo.getShiFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
            fundSource.setFundVal(reqVo.getShiFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 企业自筹
        if (StringUtil.isNotEmpty(reqVo.getQiFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
            fundSource.setFundVal(reqVo.getQiFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 其他
        if (StringUtil.isNotEmpty(reqVo.getOtherFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_OTHER);
            fundSource.setFundVal(reqVo.getOtherFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
    }



	@Override
	public String trialInvestPlan(String jsonStr) throws Exception {
		String investPlanId = JsonUtil.obtainValueFromJsonObject(jsonStr, "investPlanId");
		String statusCd = JsonUtil.obtainValueFromJsonObject(jsonStr, "statusCd");
		String examineDescription = JsonUtil.obtainValueFromJsonObject(jsonStr, "examineDescription");
		InvestPlan investPlan = new InvestPlan();
		investPlan.setInvestPlanId(investPlanId);
		investPlan.setStatusCd(statusCd);
		investPlan.setExamineDescription(examineDescription);
		investPlanOperDAO.updateInvestPlan(investPlan);
		
		//初审时 允许修改资金
		String operType = JsonUtil.obtainValueFromJsonObject(jsonStr, "operType");
		// if(StringUtil.isNotEmpty(operType) &&
		// "firstAudit".equalsIgnoreCase(operType)){
			// 需求变更--资金计划初审界面允许修改投资计划的各项金额数据，修改数据需要对原费用数据做一下备份（状态变更做备份）
			// 2.备份资金信息
			// FundSource fsBak = new FundSource();
			// fsBak.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST);
			// fsBak.setFundSourceObj(investPlanId);
			// fsBak.setStatusCd(30);//备份
			// fundSourceOperDAO.updateFundSource(fsBak);
			
			// 3.获取入参 资金构成
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		String errorMsg = "获取初审资金入参时：";
		Double fundSourceBu = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceBu", errorMsg);
		Double fundSourceSheng = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceSheng", errorMsg);
		Double fundSourceGao = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceGao", errorMsg);
		Double fundSourceQi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceQi", errorMsg);
		Double fundSourceShi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceShi", errorMsg);
		Double fundSourceOther = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceOther", errorMsg);
			
			// 4.更新资金信息
			FundSource fundSource = new FundSource();
		if (StringUtil.isNotEmpty(operType) && "1".equalsIgnoreCase(operType)) {
			fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_TRIAL);
		} else {
			fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_ALIGN);
		}
		fundSource.setFundSourceObj(investPlanId);
		fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
		fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
			int num = 0;
			// 部补助
		if (fundSourceBu != null) {
			fundSource.setFundSourceId(UUID.randomUUID().toString());
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
			fundSource.setFundVal(fundSourceBu + "");
			fundSourceOperDAO.addFundSource(fundSource);
		}
			// 省财政
		if (fundSourceSheng != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
			fundSource.setFundVal(fundSourceSheng.toString());
			fundSource.setFundSourceId(UUID.randomUUID().toString());
			fundSourceOperDAO.addFundSource(fundSource);
		}
			// 高速水运融资
		if (fundSourceGao != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
			fundSource.setFundVal(fundSourceGao.toString());
			fundSource.setFundSourceId(UUID.randomUUID().toString());
			fundSourceOperDAO.addFundSource(fundSource);
		}
			// 市州配套
		if (fundSourceShi != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
			fundSource.setFundVal(fundSourceShi.toString());
			fundSource.setFundSourceId(UUID.randomUUID().toString());
			fundSourceOperDAO.addFundSource(fundSource);
		}
			// 企业自筹
		if (fundSourceQi != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
			fundSource.setFundVal(fundSourceQi.toString());
			fundSource.setFundSourceId(UUID.randomUUID().toString());
			fundSourceOperDAO.addFundSource(fundSource);
		}
		// 其他
		if (fundSourceOther != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_OTHER);
			fundSource.setFundVal(fundSourceOther.toString());
			fundSource.setFundSourceId(UUID.randomUUID().toString());
			fundSourceOperDAO.addFundSource(fundSource);
		}
		// }
		// 批复下达
		if(StringUtil.isNotEmpty(operType) && "finalAudit".equalsIgnoreCase(operType)){
			uploadFileDeal(jsonStr, "150", investPlanId);
		}
		
		return ReturnsUtil.returnSuccess(new JSONObject()).toString();
	}

}
